import { ElMessage, ElMessageBox } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from './utils/auth'
import router from './router'
import store from './store'
// 白名单
const whiteList = ['/home', '/login', '/cart', '/forgetPassword', '/goods/detail']
// 跳转这几个页面 不需要提示
const notHandleList = ['/member/center', '/', '/home']
NProgress.configure({ showSpinner: false })

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (to.matched.length === 0) {
    next('/404') // 判断此跳转路由的来源路由是否存在，存在的情况跳转到来源路由，否则跳转到404页面
  }
  // console.log(getToken())
  // 有token
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 判断当前用户是否已拉取完user_info信息
      store.dispatch('GetInfo').then(() => {
        let userInfo = store.getters.userInfo
        // 没有完善信息 就"疯狂弹框"" 去完善
        if (userInfo.idNumber === '' || userInfo.address === '' || userInfo.province === '' || userInfo.city === '' || userInfo.county === '') {
          if (notHandleList.indexOf(to.path) !== -1) {
            next()
          } else {
            ElMessageBox.confirm('您的信息还不完善, 是否先去完善呢?', '提示', {
              confirmButtonText: '确定',
              showCancelButton: false,
              type: 'warning',
              center: true
            }).then(() => {
              next({
                path: '/member/center',
                query: {
                  tab1: 'myAccount',
                  tab2: 'perfectInfo'
                }
              })
            })
          }
        } else {
          // 获取购物车
          store.dispatch('GetCartProducts').then(res => {
            next()
          })
        }
      }).catch(err => {
        store.dispatch('LogOut').then(() => {
          next({ path: '/login' })
        })
      })
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
